package com.jy.api.controller.admin;

import com.jy.api.dao.EmployeeDao;
import com.jy.api.dao.ProductDao;
import com.jy.api.dao.StoreDao;
import com.jy.api.domain.*;
import com.jy.api.enums.DistributeType;
import com.jy.api.enums.StoreLevel;
import com.jy.api.exception.MyException;
import com.jy.api.service.CouponService;
import com.jy.api.signUpReq.admin.CouponSignUpReq;
import com.jy.api.signUpReq.admin.DistributeCouponSignUpReq;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.security.Principal;

/**
 * Created by lihu on 2017/11/17.
 */
@Slf4j
@RestController
@RequestMapping(value = "v1/admin/", produces = "application/json;charset=utf-8")
public class CouponController {

    @Autowired
    CouponService couponService;

    @Autowired
    EmployeeDao employeeDao;

    @Autowired
    StoreDao storeDao;
    @Autowired
    private ProductDao productDao;


    /**
     * 优惠卷派发
     *
     * @param signUpReq
     * @return
     */
    @PreAuthorize("hasRole('ADMIN')")
    @RequestMapping(method = RequestMethod.POST, value = "/distribute-coupon")
    public ResponseEntity distributeCoupon(@Valid @RequestBody DistributeCouponSignUpReq signUpReq,
                                           BindingResult bindingResult, Principal principal) {
        try {
            if (bindingResult.hasErrors()) {
                return new ResponseEntity(bindingResult.getFieldError().getDefaultMessage(), HttpStatus.BAD_REQUEST);
            }
            Store store = storeDao.findOne(signUpReq.getStoreId());
            if (store == null) {
                return new ResponseEntity("派发失败！店铺信息有误！！", HttpStatus.BAD_REQUEST);
            }

            if (store.getLevel() != StoreLevel.THREE) {
                return new ResponseEntity("当前店铺版本过低！请升级！", HttpStatus.BAD_REQUEST);
            }

            Employee employee = employeeDao.findByStoreIdAndUsernameAndEnabled(signUpReq.getStoreId(),
                    principal.getName(), true);
            if (employee == null) {
                return new ResponseEntity("派发失败！账号信息有误！", HttpStatus.BAD_REQUEST);
            }
            Coupon coupon = couponService.getFondId(signUpReq.getCouponId());
            if (coupon == null || !coupon.isEnabled()) {
                return new ResponseEntity("派发失败！优惠卷信息不存在！", HttpStatus.BAD_REQUEST);
            }

            if (signUpReq.getDistributeType() == DistributeType.SINGLE && signUpReq.getMemeberIds().size() == 0) {
                return new ResponseEntity("派发失败！未选择派发会员信息！", HttpStatus.BAD_REQUEST);
            }
            couponService.distributeCoupon(signUpReq, coupon, employee.getUsername(), employee.getName());
            return new ResponseEntity(HttpStatus.OK);
        } catch (Exception ex) {
            log.error("getCouponInstance  is error==> signUpReq{}", signUpReq, ex);
            return new ResponseEntity("系统运行错误", HttpStatus.INTERNAL_SERVER_ERROR);
        }

    }

    /**
     * 删除优惠卷
     *
     * @param id
     * @return
     */
    @RequestMapping(method = RequestMethod.DELETE, value = "coupon")
    public ResponseEntity deleteCoupon(@RequestParam(value = "id") String id) {
        couponService.deleteCoupon(id);
        return new ResponseEntity(HttpStatus.OK);
    }


    /**
     * 获取优惠卷信息
     *
     * @param storeId
     * @param pageable
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "coupon")
    public ResponseEntity coupon(@RequestParam(value = "storeId") String storeId,
                                 @PageableDefault(value = 10, sort = {"addTime"},
                                         direction = Sort.Direction.DESC) Pageable pageable) {
        return new ResponseEntity(couponService.getCouponAll(storeId, pageable), HttpStatus.OK);
    }

    /**
     * 新增或者修改优惠卷
     *
     * @param couponSignUpReq
     * @param bindingResult
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "coupon")
    public ResponseEntity saveCoupon(@Valid @RequestBody CouponSignUpReq couponSignUpReq,
                                     BindingResult bindingResult) {
        try {
            if (bindingResult.hasErrors()) {
                log.error("【优惠卷】参数不正确, couponSignUpReq={}", couponSignUpReq);
                return new ResponseEntity(bindingResult.getFieldError().getDefaultMessage(), HttpStatus.BAD_REQUEST);
            }

            if (couponSignUpReq.getType() == CouponType.GET_ITEM_FREE && StringUtils.isBlank(couponSignUpReq.getProductId())) {
                return new ResponseEntity("未指定冲送商品", HttpStatus.BAD_REQUEST);
            }
            Store store = storeDao.findOne(couponSignUpReq.getStoreId());
            if (store.getLevel() != StoreLevel.THREE) {
                return new ResponseEntity("店铺等级不足！请升级店铺等级", HttpStatus.BAD_REQUEST);
            }
            couponService.saveOrUpdate(couponSignUpReq);
            return new ResponseEntity(HttpStatus.OK);
        } catch (MyException ex) {
            log.error("saveCoupon is error=>couponSignUpReq:{}", couponSignUpReq, ex);
            return new ResponseEntity(ex.getMessage(), HttpStatus.BAD_REQUEST);
        } catch (Exception ex) {
            log.error("saveCoupon is error=>couponSignUpReq:{}", couponSignUpReq, ex);
            return new ResponseEntity("系统运行错误", HttpStatus.INTERNAL_SERVER_ERROR);
        }

    }

    @GetMapping("pro-spec")
    public ResponseEntity getProductSpec(@RequestParam("productId") String productId) {
        Product product = productDao.findOne(productId);
        return ResponseEntity.ok(product.getSpecs());
    }


}
